<script setup lang="ts">
import {computed, onMounted, reactive, ref, watch} from "vue";
import {ElMessage, ElMessageBox, ElTable, FormInstance} from "element-plus";
import {Loading, Refresh, Search, Plus} from "@element-plus/icons-vue";
import {
  adminGoodsLists,
  adminGetAllShopGenres,
  adminGetGoodsListByGenre,
  adminSearchGoods,
  adminSearchGoodsByName,
  adminAddGoods,
  adminEditGoods,
  adminDeleteGoods,
  adminSoldOutGoods,
  adminPutOnShelfGoods,
} from "@/router/api";

const input = ref("");
const value = ref("");
const status = [// 借阅状态
  {text: '正常', value: '正常'},
  {text: '下架', value: '下架'},
  {text: '删除', value: '删除'},
];
// 添加一个抑制watch的标志
const suppressWatch = ref(false);
const addDialog = ref(false);
const editDialog = ref(false);
const cities = ref<{ value: string; label: string; category_id: number }[]>([]);//类型
const tableRef = ref<InstanceType<typeof ElTable>>();
const tableData = ref<Array<{
  id: number;
  name: string;
  category_id: number;
  category_name: string;
  no: string;
  market_price: number;
  sale_price: number;
  stock: number;
  image: string;
  hottest: string;
  newest: string;
  description: string;
  sale_time: string;
  status: string;
}>>([]);
const loading = ref(false)
const isRefreshing = ref(false);
const filterStatus = (value: string, row: any) => {// 状态标签筛选函数
  return row.status === value;
};
// 模拟刷新动画
const handleRefresh = () => {
  getData();
  isRefreshing.value = true;
  loading.value = true;
  setTimeout(() => {
    isRefreshing.value = false;
    loading.value = false;
  }, 1000);
};
const showMessage = (type: any, message: any) => {// 显示消息提示
  ElMessage({
    type,
    message,
    duration: 1000,
  });
};
const mapData = (data: Array<any>) => {
  return data.map((item) => ({
    id: item.id,
    name: item.name,
    category_id: item.category_id,
    category_name: item.category_name,
    no: item.no,
    market_price: item.market_price,
    sale_price: item.sale_price,
    stock: item.stock,
    image: item.image,
    hottest: item.hottest === 'Y' ? '是' : '否',
    newest: item.newest === 'Y' ? '是' : '否',
    description: item.description,
    sale_time: item.sale_time,
    status: item.status === 'Y' ? '正常' : item.status === 'A' ? '下架' : '删除',
  }));
};
// 获取数据
const getData = async () => {
  try {
    const response = await adminGoodsLists();
    if (Array.isArray(response))
      tableData.value = mapData(response);
  } catch (error) {
    showMessage("error", "获取数据失败");
  }
}
//删除商品
const handleDelete = async (row: any) => {
  try {
    await adminDeleteGoods(row.id);
    await getData();
    showMessage("success", "删除成功");
  } catch (error) {
    showMessage("error", "删除失败");
  }
}
//下架商品
const handleDown = async (row: any) => {
  try {
    if (row.status === '正常') {
      await adminSoldOutGoods(row.id);
      showMessage("success", "下架成功");
    } else if (row.status === '下架') {
      await adminPutOnShelfGoods(row.id);
      showMessage("success", "上架成功");
    }
    await getData();
  } catch (error) {
    showMessage("error", "下架失败");
  }
}
const handleClear = () => {
  value.value = '';
  showMessage('info', '已取消选择！');
};
// 搜索商品
const searchData = async () => {
  if (input.value.trim() === '') {
    suppressWatch.value = true; // 禁止watch触发
    value.value = '';
    await getData();
  } else {
    try {
      suppressWatch.value = true; // 禁止watch触发
      const response = await adminSearchGoods(input.value);
      value.value = '';
      if (Array.isArray(response)) {
        tableData.value = mapData(response);
      }
    } catch (error) {
      showMessage('error', '搜索失败！');
    }
  }
};
const goods = ref<{ value: string }[]>([]);
const querySearch = async (queryString: string, cb: (list: { value: string }[]) => void) => {
  if (!queryString) return cb([]);
  try {
    const response = await adminSearchGoodsByName(queryString);
    // 后端返回的是纯字符串数组，直接映射为 { value: string } 格式
    goods.value = Array.isArray(response)
        ? response.map(name => ({value: name})) // 直接使用字符串
        : [];
    cb(goods.value);
  } catch (error) {
    console.error('搜索建议失败:', error);
    cb([]);
  }
};

// 根据数据结构调整参数类型
const handleSelect = (item: { value: string }) => {
  input.value = item.value;
};
//获取所有商品类型
const fetchGenres = async () => {
  try {
    const response = await adminGetAllShopGenres();
    if (Array.isArray(response)) {
      cities.value = response.map((genre: any) => ({
        value: genre.name,
        label: genre.name,
        category_id: genre.id,
      }));
    }
  } catch (error) {
    showMessage('error', '获取商品类型失败！');
  }
};
// 根据类型获取商品列表
const fetchDataByGenre = async () => {
  if (value.value.trim() === '') {
    await getData();
  } else {
    try {
      const response = await adminGetGoodsListByGenre(value.value);
      input.value = '';
      if (Array.isArray(response)) {
        tableData.value = mapData(response);
      }
    } catch (error) {
      showMessage('error', '获取失败！');
    }
  }
};
watch(value, () => {
  if (suppressWatch.value) {
    suppressWatch.value = false; // 重置标志
    return;
  }
  fetchDataByGenre();
});
onMounted(() => {
  fetchGenres();
  getData();
})
const expandedRowKeys = ref([]);
const handleExpandChange = (row: any, expandedRows: any) => {
  // 如果当前行被展开
  if (expandedRows.length > 0) {
    // 清空之前展开的行
    expandedRowKeys.value = [];
    // 将当前行的 key 添加到展开列表
    expandedRowKeys.value.push(row.id);
  } else {
    // 如果当前行被关闭，清空展开列表
    expandedRowKeys.value = [];
  }
};
const rules = {
  name: [
    {required: true, message: '请输入商品名称', trigger: 'blur'},
    {min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur'},
  ],
  category_id: [
    {required: true, message: '请选择商品类型', trigger: 'change'},
  ],
  no: [
    {required: true, message: '请输入商品编号', trigger: 'blur'},
    {min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur'},
  ],
  market_price: [
    {required: true, message: '请输入市场价格', trigger: 'blur'},
  ],
  sale_price: [
    {required: true, message: '请输入销售价格', trigger: 'blur'},
  ],
  stock: [
    {required: true, message: '请输入库存', trigger: 'blur'},
  ],
  image: [
    {required: true, message: '请上传商品图片', trigger: 'blur'},
  ],
}

// 添加商品
const addFormRef = ref<FormInstance>();
const addForm = reactive({
  id: '',
  name: '',
  category_id: '',
  no: '',
  market_price: 0,
  sale_price: 0,
  stock: '',
  image: '',
  description: '',
});
// 添加商品
const handleAdd = async () => {
  await addFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        input.value = '';
        value.value = '';
        await adminAddGoods(addForm);
        await getData();
        resetForm();
        addDialog.value = false;
      } catch (error) {
        showMessage('error', '添加失败，请稍后再试！');
      }
    } else {
      showMessage('warning', '请确保所有字段都填写完整！');
    }
  });
};
const downAddClose = async (done: any) => {// 关闭抽屉并保存添加操作
  try {// 弹出确认框
    await ElMessageBox.confirm('您确定要关闭吗？');
  } catch {
    return;  // 如果用户取消操作，直接返回
  }
  // 校验表单
  if (!await addFormRef.value?.validate()) {
    showMessage('warning', '请确保所有字段都填写完整！');
    return;
  }
  try {
    input.value = '';
    value.value = '';
    await adminAddGoods(addForm);
    await getData()
    done();  // 回调
    addDialog.value = false;
    resetForm();
    showMessage('success', '添加成功');
  } catch (error) {
    showMessage('error', '添加失败，请稍后再试！');
  } finally {
    addDialog.value = false;  // 关闭对话框
  }
};
const closeAddDialog = () => {// 关闭添加书籍的抽屉
  addDialog.value = false;
  resetForm();
};
const resetForm = () => {// 重置表单数据
  addFormRef.value?.resetFields();
}

// 编辑商品
const editFormRef = ref<FormInstance>();
const editForm = reactive({
  id: '',
  name: '',
  category_id: '',
  no: '',
  market_price: '',
  sale_price: '',
  stock: '',
  image: '',
  description: '',
});
const intiEdit = reactive({
  id: '',
  name: '',
  category_id: '',
  no: '',
  market_price: '',
  sale_price: '',
  stock: '',
  image: '',
  description: '',
})
const openEdit = (row: any) => {
  editDialog.value = true;
  editForm.id = row.id;
  editForm.name = row.name;
  editForm.category_id = row.category_id;
  editForm.no = row.no;
  editForm.market_price = row.market_price;
  editForm.sale_price = row.sale_price;
  editForm.stock = row.stock;
  editForm.image = row.image;
  editForm.description = row.description;

  intiEdit.id = row.id;
  intiEdit.name = row.name;
  intiEdit.category_id = row.category_id;
  intiEdit.no = row.no;
  intiEdit.market_price = row.market_price;
  intiEdit.sale_price = row.sale_price;
  intiEdit.stock = row.stock;
  intiEdit.image = row.image;
  intiEdit.description = row.description;
}
//修改商品
const handleEdit = () => {
  editFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        await adminEditGoods(editForm);
        await getData();
        intiEdit.id = editForm.id;
        intiEdit.name = editForm.name;
        intiEdit.category_id = editForm.category_id;
        intiEdit.no = editForm.no;
        intiEdit.market_price = editForm.market_price;
        intiEdit.sale_price = editForm.sale_price;
        intiEdit.stock = editForm.stock;
        intiEdit.image = editForm.image;
        intiEdit.description = editForm.description;
        editDialog.value = false;
        showMessage("success", "编辑成功");
      } catch (error) {
        showMessage("error", "编辑失败");
      }
    } else {
      showMessage("warning", "请确保所有字段都填写完整！");
    }
  });
}
const downEditClose = async (done: any) => {
  try {// 弹出确认框
    await ElMessageBox.confirm('您确定要关闭吗？');
  } catch {
    return;  // 如果用户取消操作，直接返回
  }
  // 校验表单
  if (!await editFormRef.value?.validate()) {
    showMessage('warning', '请确保所有字段都填写完整！');
    return;
  }
  try {
    await adminEditGoods(editForm);
    await getData()
    done();  // 回调
    intiEdit.id = editForm.id;
    intiEdit.name = editForm.name;
    intiEdit.category_id = editForm.category_id;
    intiEdit.no = editForm.no;
    intiEdit.market_price = editForm.market_price;
    intiEdit.sale_price = editForm.sale_price;
    intiEdit.stock = editForm.stock;
    intiEdit.image = editForm.image;
    intiEdit.description = editForm.description;
    editDialog.value = false;
    showMessage('success', '添加成功');
  } catch (error) {
    showMessage('error', '添加失败，请稍后再试！');
  } finally {
    editDialog.value = false;  // 关闭对话框
  }
}
const addImgSuccess = (response: any) => {
  if (response.status === "success") { // 与后端统一响应格式
    addForm.image = response.data; // 直接获取返回的URL
  } else {
    console.error('上传失败:', response.message);
  }
};
const editImgSuccess = (response: any) => {
  if (response.status === "success") { // 与后端响应格式对应
    editForm.image = response.data; // 直接获取返回的URL
  } else {
    console.error('上传失败:', response.message);
  }
};
//是否显示删除人员信息
const isShowDelete = ref(false);
// 动态过滤表格数据
const filteredTableData = computed(() => {
  if (isShowDelete.value) {
    return tableData.value;
  }
  return tableData.value.filter((item) => item.status !== '删除');
});
// 监听 isShowDelete 的变化，动态刷新表格数据
watch(isShowDelete, async (newValue) => {
  if (newValue) {
    await getData(); // 如果显示删除状态的用户，重新获取数据
  }
});
</script>

<template>
  <div class="admin-container">
    <el-form @submit.prevent="searchData">
      <el-autocomplete v-model="input" placeholder="请输入" :fetch-suggestions="querySearch"
                       @select="handleSelect" clearable size="large"
                       style="width: 300px;height: 60%;margin: 0 20px"
                       select-when-unmatched
                       highlight-first-item>
        <template #prepend>
          <el-button native-type="submit">
            <el-icon>
              <Search/>
            </el-icon>
          </el-button>
        </template>
      </el-autocomplete>
    </el-form>
    <el-select v-model="value" placeholder="请选择商品类型" clearable size="large"
               @clear="handleClear"
               style="width: 200px;margin:0 20px">
      <el-option v-for="item in cities" :key="item.value" :label="item.label"
                 :value="item.value"/>
    </el-select>
    <el-button @click="addDialog= true" type="primary" plain class="buttons">添加商品
    </el-button>
    <el-switch
        active-text="显示删除"
        v-model="isShowDelete"
        style="--el-switch-on-color: #13ce66;margin-left: 20px;"
    />
    <div class="refresh-container">
      <el-icon v-if="isRefreshing" class="loading-icon">
        <Loading/>
      </el-icon>
      <el-icon v-else class="refresh-icon">
        <Refresh @click="handleRefresh"/>
      </el-icon>
    </div>
  </div>
  <el-table ref="tableRef" :data="filteredTableData" style="width: 100%" highlight-current-row
            v-loading="loading" row-key="id" :expand-row-keys="expandedRowKeys"
            @expand-change="handleExpandChange">
    <el-table-column prop="name" label="商品名称" show-overflow-tooltip align="center"/>
    <el-table-column prop="category_name" label="商品类型" show-overflow-tooltip align="center"/>
    <el-table-column prop="no" label="商品编号" show-overflow-tooltip align="center"/>
    <el-table-column prop="market_price" label="市场价格" show-overflow-tooltip align="center"
                     width="100"/>
    <el-table-column prop="sale_price" label="销售价格" show-overflow-tooltip align="center"
                     width="100"/>
    <el-table-column prop="stock" label="库存" show-overflow-tooltip align="center" width="100"/>
    <el-table-column prop="status" label="状态" :filters="status" :filter-method="filterStatus"
                     filter-placement="bottom-end" show-overflow-tooltip align="center" width="90">
      <template #default="scope">
        <el-tag
            :type="scope.row.status === '正常' ? 'success' : scope.row.status === '下架' ? 'warning' : 'danger'"
            disable-transitions>
          {{ scope.row.status }}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column type="expand" label="详情" min-width="50">
      <template #default="props">
        <div style="margin-left: 20px; display: flex; flex-wrap: wrap;">
          <p style="font-weight: bold; font-size: large; width: 100%; margin-bottom: 10px;">
            商品详情信息</p>
          <div style="width: 100%;">
            <img :src="props.row.image" alt="" class="bookImg">
          </div>
          <p v-for="(value, label) in {
            '商品名称': props.row.name,
            '商品编号': props.row.no,
            '商品类型': props.row.category_name,
            '市场价格': props.row.market_price,
            '销售价格': props.row.sale_price,
            '库存': props.row.stock,
            '是否热销': props.row.hottest,
            '是否新品': props.row.newest,
            '上架时间': props.row.sale_time,
            '商品状态': props.row.status
              }" :key="label" style="width: 300px; margin-right: auto; margin-bottom: 10px">
            <strong>{{ label }}{{ label ? '：' : '' }}</strong> {{ value }}
          </p>

          <p style="width: 100%; margin-bottom: 10px;">
            <strong>商品描述:</strong> {{ props.row.description }}
          </p>
        </div>
      </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作" show-overflow-tooltip align="center" width="200">
      <template #default="scope">
        <el-button size="small" @click="openEdit(scope.row)" type="primary"
                   :disabled="scope.row.status !== '正常'">编辑
        </el-button>
        <el-button size="small" @click="handleDown(scope.row)" type="warning"
                   :plain="scope.row.status!=='正常'"
                   :disabled="scope.row.status === '删除'">
          {{ scope.row.status === '正常' ? '下架' : '上架' }}
        </el-button>
        <el-button size="small" @click="handleDelete(scope.row)" type="danger"
                   :disabled="scope.row.status === '删除'">删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 添加商品弹窗 -->
  <el-drawer v-model="addDialog" title="添加书籍" :before-close="downAddClose" direction="ltr" modal
             :show-close="false" size="30%">
    <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="rules"
        status-icon
        scroll-to-error
        label-width="auto"
        size="default">
      <el-form-item label="商品图片" prop="image">
        <el-upload
            action="http://localhost:8080/api/upload"
            :show-file-list="false"
            :on-success="addImgSuccess"
            name="file">
          <img v-if="addForm.image" :src="addForm.image" alt="商品图片" class="bookImg"/>
          <el-icon v-else class="bookImg">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="addForm.name" placeholder="请输入商品名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="商品类型" prop="category_name">
        <el-select v-model="addForm.category_id" placeholder="请选择商品类型">
          <el-option v-for="item in cities" :key="item.category_id" :label="item.label"
                     :value="item.category_id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="商品编号" prop="no">
        <el-input v-model="addForm.no" placeholder="请输入商品编号" clearable></el-input>
      </el-form-item>
      <el-form-item label="市场价格" prop="market_price">
        <el-input-number v-model="addForm.market_price" :min="0" :precision="2"
                         controls-position="right" size="default"/>
      </el-form-item>
      <el-form-item label="销售价格" prop="sale_price">
        <el-input-number v-model="addForm.sale_price" :min="0" :precision="2"
                         controls-position="right" size="default"/>
      </el-form-item>
      <el-form-item label="库存" prop="stock">
        <el-input-number v-model="addForm.stock" :min="0" controls-position="right" size="default"/>
      </el-form-item>
      <el-form-item label="商品描述" prop="description">
        <el-input type="textarea" v-model="addForm.description" placeholder="请输入商品描述"
                  clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleAdd">保存</el-button>
        <el-button @click="closeAddDialog">取消</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
  <!-- 编辑商品弹窗 -->
  <el-drawer v-model="editDialog" title="添加书籍" :before-close="downEditClose" direction="rtl"
             modal
             :show-close="false" size="30%">
    <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="rules"
        status-icon
        scroll-to-error
        label-width="auto"
        size="default">
      <el-form-item label="商品图片" prop="image">
        <el-upload
            action="http://localhost:8080/api/upload-with-replace"
            :show-file-list="false"
            :on-success="editImgSuccess"
            :data="{ oldImageUrl: editForm.image }"
            name="file">
          <img v-if="editForm.image" :src="editForm.image" alt="商品图片" class="bookImg"/>
          <el-icon v-else class="bookImg">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="editForm.name" placeholder="请输入商品名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="商品类型" prop="category_name">
        <el-select v-model="editForm.category_id" placeholder="请选择商品类型">
          <el-option v-for="item in cities" :key="item.category_id" :label="item.label"
                     :value="item.category_id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="商品编号" prop="no">
        <el-input v-model="editForm.no" placeholder="请输入商品编号" clearable></el-input>
      </el-form-item>
      <el-form-item label="市场价格" prop="market_price">
        <el-input-number v-model="editForm.market_price" :min="0" :precision="2"
                         controls-position="right" size="default"/>
      </el-form-item>
      <el-form-item label="销售价格" prop="sale_price">
        <el-input-number v-model="editForm.sale_price" :min="0" :precision="2"
                         controls-position="right" size="default"/>
      </el-form-item>
      <el-form-item label="库存" prop="stock">
        <el-input-number v-model="editForm.stock" :min="0" controls-position="right"
                         size="default"/>
      </el-form-item>
      <el-form-item label="商品描述" prop="description">
        <el-input type="textarea" v-model="editForm.description" placeholder="请输入商品描述"
                  clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleEdit">保存</el-button>
        <el-button @click="editDialog = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style scoped>
.bookImg {
  width: 120px;
  height: 150px;
  overflow: hidden;
  border: 2px solid #cccccc;
  object-fit: cover; /* 保持比例，裁剪多余部分 */
}

.admin-container {
  width: 100%;
  display: flex;
  align-items: center;
  margin: 20px 0;
}

.refresh-container {
  margin-top: 4px;
  margin-left: 20px;
}

.loading-icon {
  color: #707581;
  font-size: 26px;
  animation: spin 1s infinite linear;
}

.refresh-icon {
  color: #707581;
  cursor: pointer;
  font-size: 26px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
